package com.kingwang.demo.springsecuritytokendemo.controller;

import com.kingwang.demo.springsecuritytokendemo.dto.LoginDto;
import com.kingwang.demo.springsecuritytokendemo.security.AuthenticationResultCode;
import com.kingwang.demo.springsecuritytokendemo.security.TokenAuthenticationResult;
import com.kingwang.demo.springsecuritytokendemo.security.TokenSession;
import com.kingwang.demo.springsecuritytokendemo.security.TokenSessionManager;
import com.kingwang.demo.springsecuritytokendemo.security.sso.SsoAuthenticationResult;
import com.kingwang.demo.springsecuritytokendemo.security.sso.SsoAuthenticatorFactory;
import com.kingwang.demo.springsecuritytokendemo.security.sso.authenticator.SsoAuthenticator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

/**
 * @author King
 */
@RestController
public class LoginController {
    private final UserDetailsService userDetailsService;

    private final TokenSessionManager sessionManager;

    @Autowired
    public LoginController(UserDetailsService userDetailsService, TokenSessionManager sessionManager) {
        this.userDetailsService = userDetailsService;
        this.sessionManager = sessionManager;
    }

    /**
     * 使用用户名密码登录接口
     *
     * @param dto
     * @return
     */
    @PostMapping("/token")
    public TokenAuthenticationResult login(LoginDto dto) {
        UserDetails userDetails = this.userDetailsService.loadUserByUsername(dto.getUsername());

        // 省略认证逻辑...

        // 生成Token并保存
        String tokenType = "Bearer";

        TokenSession session = this.sessionManager.createSession(tokenType, userDetails);

        // 返回认证成功结果
        TokenAuthenticationResult result = new TokenAuthenticationResult();
        result.setSuccess(true);
        result.setType(tokenType);
        result.setToken(session.getToken());

        return result;
    }

    /**
     * 第三方单点登录接口
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/auth/thirdparty")
    public Object loginThirdParty(HttpServletRequest request) {
        SsoAuthenticator authenticator = SsoAuthenticatorFactory.create(request);

        SsoAuthenticationResult authenticationResult = authenticator.authenticate();

        if (AuthenticationResultCode.SUCCESS.equals(authenticationResult.getCode())) {
            // 生成token并保存
        }

        return null;
    }
}
